﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Syufy.BINLookup.Web.Interfaces;

namespace Syufy.BINLookup.Web.Tests.Mocks
{
    public class MockUnitOfWork<TContext> : IUnitOfWork where TContext : class, new()
    {
        private TContext _context;
        private Dictionary<Type, object> _repositories;

        public MockUnitOfWork()
        {
            _context = new TContext();
            _repositories = new Dictionary<Type, object>();
        }

        public IGenericRepository<TEntity> GetRepository<TEntity>() where TEntity : class
        {
            if (_repositories.Keys.Contains(typeof(TEntity)))
            {
                return _repositories[typeof(TEntity)] as IGenericRepository<TEntity>;
            }

            var entityName = typeof(TEntity).Name;
            var property = _context.GetType().GetProperty(entityName);
            MockRepository<TEntity> repository = null;
            if (property != null)
            {
                var entityValue = property.GetValue(_context, null);
                repository = new MockRepository<TEntity>(entityValue as List<TEntity>);
            }
            else
            {
                repository = new MockRepository<TEntity>(new List<TEntity>());
            }
            _repositories.Add(typeof(TEntity), repository);
            return repository;
        }

        public void SetRepositoryData<TEntity>(List<TEntity> data) where TEntity : class
        {
            IGenericRepository<TEntity> repository = GetRepository<TEntity>();

            var mockRepository = repository as MockRepository<TEntity>;
            if (mockRepository != null)
            {
                mockRepository._context = data;
            }
        }

        public void Save()
        {
        }

        public Task SaveAsync()
        {
            return null;
        }

        public void Dispose()
        {
        }
    }
}
